from django.contrib.auth.hashers import make_password
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.views import auth_login, auth_logout, login_required
from .models import CustomUser
from .forms import LoginForm, RegistForm, UpdatePasswordForm, PersonFrom


# Create your views here.

def login(request):
    lgf = LoginForm()
    error = None
    if request.method == 'POST':
        lgf = LoginForm(request.POST)
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = CustomUser.objects.filter(username=username).first()
        if user:
            if user.check_password(password):
                auth_login(request, user)
                next_url = request.GET.get('next')
                if next_url:
                    return redirect('/')
                else:
                    return redirect(to='/')
            else:
                error = '密码错误'
        else:
            error = '用户不存在'
    return render(request, 'user/login.html', context={'error': error, 'lgf': lgf})


def register(request):
    rgf = RegistForm()
    if request.method == 'POST':
        rgf = RegistForm(request.POST)
        if rgf.is_valid():
            print(dir(rgf))
            password = rgf.cleaned_data.pop('password')
            password2 = rgf.cleaned_data.pop('password2')
            if password != password2:
                rgf.errors.update({
                    'password': ['密码不一致', ]
                })
            else:
                user = rgf.save(commit=False)
                user.password = make_password(password)
                user.save()
                return redirect(to='/user/login/')

    return render(request, 'user/register.html', context={'rgf': rgf})


def logout(request):
    auth_logout(request)
    return redirect('/')

@login_required
def person(request):
    psf = PersonFrom(initial={
        'username': request.user.username,
        'email': request.user.email,
        'last_name': request.user.last_name,
        'first_name': request.user.first_name,
    })
    if request.method == 'POST':
        psf = PersonFrom(data=request.POST,instance=request.user,files=request.FILES)
        if psf.is_valid():
            psf.save()
            return redirect(to='/')
    return render(request, 'user/person.html', context={'psf': psf})
